// modbus_base.h
#ifndef MODBUS_BASE_H
#define MODBUS_BASE_H

#include <cstdint>
#include <string>
#include <vector>
#include <mutex>
#include <memory>

enum FunctionCode : uint8_t {
    READ_HOLDING_REGISTERS = 0x03,
    WRITE_SINGLE_REGISTER = 0x06,
    WRITE_MULTIPLE_REGISTERS = 0x10
};

class ModbusBase {
public:
    ModbusBase();
    virtual ~ModbusBase();

protected:
    std::vector<uint8_t> create_request(FunctionCode function_code, 
                                       uint8_t machine_addr,
                                       uint16_t start_addr, 
                                       uint16_t reg_count,
                                       const std::vector<uint16_t>& data = {}) const;
    
    uint16_t calculate_crc(const uint8_t* buffer, uint16_t length) const;

    // 新增帧处理辅助函数
    size_t predict_frame_length(const uint8_t* data, size_t len, uint8_t slave_addr = 0) const;
    bool validate_frame_crc(const uint8_t* data, size_t length) const;

    // uint8_t device_address_;
    // bool loopback_test_ = false;
    mutable std::mutex serial_mutex_;
private:
    // 常量用于帧预测
    static constexpr size_t MIN_FRAME_SIZE = 4; // 地址 + 功能码 + CRC
};

#endif // MODBUS_BASE_H
